/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presentacion;

import java.util.ArrayList;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import logica.ControladorArticulos;
import logica.ControladorCaracteristicas;
import logica.ControladorEtiquetas;
import logica.ControladorPrecios;
import logica.ControladorProductos;

/**
 *
 * @author Andres
 */
public class PrototipoIngresoMasivoEImpresion extends AZPanel {

    private ControladorArticulos articulos;
    private ControladorPrecios precios;
    private ControladorProductos productos;

    /**
     * Creates new form PrototipoIngresoMasivoEImpresion
     */
    public PrototipoIngresoMasivoEImpresion() {
        initComponents();
    }

    @Override
    protected void cargarCaracteristicas() {
        agregarCombosALineasFactura(this.jTable3);
    }

    public void setArticulos(ControladorArticulos a) {
        this.articulos = a;
    }

    public void setPrecios(ControladorPrecios p) {
        this.precios = p;
    }

    public void setProductos(ControladorProductos p) {
        this.productos = p;
    }

    private void agregarCombosALineasFactura(JTable a) {
        JComboBox combo = new JComboBox();
        combo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cargarPrecio();
            }
        });
        cargarCombo("descripciones", combo);
        TableColumn col = a.getColumnModel().getColumn(0);
        col.setCellEditor(new DefaultCellEditor(combo));

        combo = new JComboBox();
        combo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cargarPrecio();
            }
        });
        cargarCombo("talles", combo);
        col = a.getColumnModel().getColumn(1);
        col.setCellEditor(new DefaultCellEditor(combo));

        combo = new JComboBox();
        cargarCombo("colores", combo);
        col = a.getColumnModel().getColumn(2);
        col.setCellEditor(new DefaultCellEditor(combo));

        combo = new JComboBox();
        cargarCombo("locales", combo);
        col = a.getColumnModel().getColumn(3);
        col.setCellEditor(new DefaultCellEditor(combo));
    }

    private void cargarPrecio() {
        int row = this.jTable3.getSelectedRow();
        if (row == -1) {
            return;
        }
        String codigo = this.jTable3.getModel().getValueAt(row, 0).toString();
        String talle = this.jTable3.getModel().getValueAt(row, 1).toString();
        if (!codigo.equals("") && !talle.equals("")) {
            String precio = this.precios.cargar(codigo, talle);
            DefaultTableModel tabla = (DefaultTableModel) this.jTable3.getModel();
            tabla.setValueAt(precio, row, 5);
        }
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        PrototipoIngresoMasivoEImpresion p = new PrototipoIngresoMasivoEImpresion();
        p.setCaracteristicas(new ControladorCaracteristicas());
        f.add(p);
        f.setVisible(true);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane7 = new javax.swing.JScrollPane();
        jTable3 = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setMinimumSize(new java.awt.Dimension(975, 528));
        setPreferredSize(new java.awt.Dimension(975, 528));

        jTable3.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"", "", "", "",  new Integer(0), "",  new Boolean(true)},
                {"", "", "", "",  new Integer(0), "",  new Boolean(true)},
                {"", "", "", "",  new Integer(0), "",  new Boolean(true)},
                {"", "", "", "",  new Integer(0), "",  new Boolean(true)}
            },
            new String [] {
                "Producto", "Talle", "Color", "Lugar", "Cantidad", "Precio", "Etiquetas c/precio"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jScrollPane7.setViewportView(jTable3);

        jButton3.setText("Agregar linea");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton6.setText("Borrar lineas");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jButton1.setText("Actualizar stock e imprimir etiquetas");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton6, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane7, javax.swing.GroupLayout.DEFAULT_SIZE, 786, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)))
                .addContainerGap(179, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton3)
                    .addComponent(jButton6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane7, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(54, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        DefaultTableModel a = (DefaultTableModel) this.jTable3.getModel();
        a.addRow(new Object[]{"", "", "", "", new Integer(0), "", new Boolean(true)});

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        jTable3.setModel(new javax.swing.table.DefaultTableModel(
                new Object[][]{
                    {"", "", "", "", new Integer(0), "", new Boolean(true)},
                    {"", "", "", "", new Integer(0), "", new Boolean(true)},
                    {"", "", "", "", new Integer(0), "", new Boolean(true)},
                    {"", "", "", "", new Integer(0), "", new Boolean(true)}
                },
                new String[]{
                    "Producto", "Talle", "Color", "Lugar", "Cantidad", "Precio", "Etiquetas c/precio"
                }) {
            Class[] types = new Class[]{
                java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.String.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }
        });
        agregarCombosALineasFactura(this.jTable3);
        this.jLabel1.setText("");
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.jLabel1.setText("");
        TableModel tabla = this.jTable3.getModel();
        ArrayList<String[]> lineas = new ArrayList<String[]>();
        String p, t, c, l, prec, cant, c_precio;
        for (int i = 0; i < tabla.getRowCount(); i++) {
            p = tabla.getValueAt(i, 0).toString();
            t = tabla.getValueAt(i, 1).toString();
            c = tabla.getValueAt(i, 2).toString();
            l = tabla.getValueAt(i, 3).toString();
            cant = tabla.getValueAt(i, 4).toString();
            prec = tabla.getValueAt(i, 5).toString();
            c_precio = tabla.getValueAt(i, 6).toString();
            if (!p.equals("") && !t.equals("") && !c.equals("") && !l.equals("") && !cant.equals("0")) {
                if (Integer.parseInt(cant) < 0) {
                    this.jLabel1.setText("Hay valores negativos en la linea " + (i + 1) + ".");
                    return;
                }
                lineas.add(new String[]{p, t, c, l, cant, prec, c_precio});
            } else {
                if (!(p.equals("") && t.equals("") && c.equals("") && l.equals("") && cant.equals("0"))) {
                    this.jLabel1.setText("La linea " + (i + 1) + " tiene campos sin cargar.");
                    return;
                }
            }
        }
        int i;
        for (i = 0; i < lineas.size(); i++) {
            p = lineas.get(i)[0];
            t = lineas.get(i)[1];
            c = lineas.get(i)[2];
            l = lineas.get(i)[3];
            cant = lineas.get(i)[4];
            prec = lineas.get(i)[5];
            c_precio = lineas.get(i)[6];
            boolean resultado = this.articulos.actualizarStock(p, t, c, l, Integer.parseInt(cant));
            if (!resultado) {
                break;
            }
            this.precios.modificar(p, t, prec);
            String descripcion = this.productos.cargarDatos(p).get("descripcion");
            Boolean c_p = Boolean.valueOf(c_precio);
            resultado = ControladorEtiquetas.imprimir(null, p, descripcion, prec, t, c, (Integer.parseInt(cant) + 1) / 2, c_p, true);
            if (!resultado) {
                break;
            }
        }
        if (i != lineas.size()) {
            // Si ocurrió un error revierto los cambios
            for (int j = 0; j <= i; j++) {
                p = lineas.get(j)[0];
                t = lineas.get(j)[1];
                c = lineas.get(j)[2];
                l = lineas.get(j)[3];
                cant = lineas.get(j)[4];
                this.articulos.actualizarStock(p, t, c, l, -Integer.parseInt(cant));
            }
            //ControladorEtiquetas.limpiar(archivo);
            this.jLabel1.setText("Ocurrio un error.");
            return;
        }
        this.jLabel1.setText("Opercación exitosa");
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane7;
    private javax.swing.JTable jTable3;
    // End of variables declaration//GEN-END:variables
}
